package cz.tpj.upl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Temporary {
	private static Temporary IM;
	
	public Temporary(){}
	
	public static Temporary getInstance() {
		if (IM == null)
			IM = new Temporary();
		return IM;
	}
	
	/** Prida slozku do tempu. Slozka, kera se ma natahnout 
	 * do tempu, se zada metode do argumentu metody. 
	 */
	public String addFolderInTemp(String sourcePath, String destinationFolder){
		//kdyz soubor ci slozka neexistuje, pak zkonci
		File source = new File(sourcePath);
		File destination = new File(destinationFolder + "/" + source.getName());
		copyFolder(source, destination);
		return null;
	}

	private void copyFolder(File source, File destination) {
		//pokud neexistuje zdroj a soucasne zdroj neni slozka, pak zkonci
		if(!source.exists() && !source.isDirectory()){
			return;
		}
		//vytvor cilovou slozku, pokud jiz neexistuje
		if(!destination.exists())
			destination.mkdirs();
		//dej vsechny soubory co obsahuje zdrojova slozka
		File[] sourceFiles = source.listFiles();
		//projdi vsechny soubory
		for(int i=0; i < sourceFiles.length; i++){
			String newDestination = destination.getAbsolutePath() + "/" + sourceFiles[i].getName();
			if(sourceFiles[i].isFile()){
				//kopiruje (z, do)
				copyFile(sourceFiles[i], new File(newDestination));
			}else{
				//kopiruj vse uvnitr slozky
				copyFolder(sourceFiles[i], new File(newDestination));
			}
		}
	}

	private void copyFile(File from, File to) {
		FileInputStream input = null;
		FileOutputStream output = null;
		try {
			if(!to.exists() && !to.createNewFile())
				return;
			input = new FileInputStream(from);
			output = new FileOutputStream(to);
			// kopirovani dat
			byte data[] = new byte[1024];
			int cout;
			while (input.available() > 0) {
				cout = input.read(data);
				output.write(data, 0, cout);
			}
		} catch (IOException e) {} 
		finally{
			try {
				input.close();
				output.close();
			} catch (Exception e) {}
		}
	}//---copyFile---
	
	public String testik(){
		String s = new String();
		
		
		
		
		return s;
	}
}
